//
//  ListTableViewController.swift
//  addressBook
//
//  Created by ZhangXu on 2017/12/20.
//  Copyright © 2017年 zhangXu. All rights reserved.
//

import UIKit

class ListTableViewController: UITableViewController {

    //联系人数组
    var personList = [Person]()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadData { (list) in
            print(list)
            
            //拼接数组 闭包中定义好的代码在需要的时候执行 self指定语境
          self.personList += list
            
            
            //刷新表格
            self.tableView.reloadData()
            
        }

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }
    
    //模拟异步 利用闭包回调
    private func loadData(completion:@escaping (_ list:[Person]) -> ()) -> (){
        
        DispatchQueue.global().async {
            
            print("正在努力加载中....")
            
            Thread.sleep(forTimeInterval: 1)
            
            var arrayM = [Person]()
            
            for i in 0..<20 {
                
                let p = Person()
                p.name = "张旭 - \(i)) "
                
                p.phone = "1504" + String(format:"%06d",arc4random_uniform(1000000))
                
                p.title = "程序"
                
                arrayM.append(p)

            }
            
            //主线程回调
            DispatchQueue.main.async(execute: {
                
                //回调闭包
                completion(arrayM)
                
                
            })
            
        }
        
        
    }
    
    //MARK: -控制器跳转方法
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        //类型转换 as
        //Swift 中string 之外 绝大多数使用as 或者 !
        //as! / as?  直接根据前面发返回值来决定
        
        let vc = segue.destination as! DetailController
        
        //设置选中的person.indexPath
        
        // if let / guard let 判空语句 一律使用as?
        if let indexPath = sender as? IndexPath {
            
            //编辑个人记录
            
            vc.person = personList[indexPath.row]
            
            //设置编辑完成的闭包
            vc.completionCallBack = {
                //刷新指定行
//                self.tableView.reloadData()
                self.tableView.reloadRows(at: [indexPath], with: .automatic)
                
            }
            
        }else{
            
            //新建个人记录
            
            vc.completionCallBack = { [weak vc] in
                
                //此处注意循环引用
                
                //1.获取明细控制器的person
                
                guard let p = vc?.person else{
                    
                    return
                    
                }   

                //2.插入数组顶部
                   self.personList.insert(p, at: 0)
                //3.刷新
                
                self.tableView.reloadData()
            }
            
            
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        print(personList.count)
        return personList.count
    }



    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)
        
        cell.textLabel?.text = personList[indexPath.row].name
        cell.detailTextLabel?.text = personList[indexPath.row].phone
        
        return cell
        // Configure the cell...

    }
    
    
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: true)
        
        //执行segue
        performSegue(withIdentifier: "segue", sender: indexPath)
        
    }
    
  
    @IBAction func addBt(_ sender: UIBarButtonItem) {
        
        //
        performSegue(withIdentifier: "segue", sender: nil)
        
    }
    


    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
